"""
钱包管理路由
"""
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List
from decimal import Decimal

from database import get_db
from auth import get_current_active_user
from models import User, Wallet, Transaction
from schemas import TransactionResponse, BaseResponse, PaginatedResponse, WalletResponse

router = APIRouter()

@router.get("/balance", response_model=WalletResponse)
async def get_wallet_balance(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取钱包余额"""
    wallet = db.query(Wallet).filter(Wallet.user_id == current_user.id).first()
    if not wallet:
        # 如果钱包不存在，创建一个
        wallet = Wallet(user_id=current_user.id, balance=Decimal('0.00'))
        db.add(wallet)
        db.commit()
        db.refresh(wallet)
    
    return WalletResponse(
        balance=float(wallet.balance),
        user_id=wallet.user_id,
        updated_at=wallet.updated_at
    )

@router.post("/deposit", response_model=BaseResponse)
@router.post("/recharge", response_model=BaseResponse)
async def deposit_to_wallet(
    amount: float,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """充值到钱包"""
    if amount <= 0:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="充值金额必须大于0"
        )
    
    wallet = db.query(Wallet).filter(Wallet.user_id == current_user.id).first()
    if not wallet:
        wallet = Wallet(user_id=current_user.id, balance=Decimal('0.00'))
        db.add(wallet)
        db.commit()
        db.refresh(wallet)
    
    # 更新余额
    wallet.balance += Decimal(str(amount))
    
    # 记录交易
    transaction = Transaction(
        wallet_id=wallet.id,
        transaction_type='deposit',
        amount=Decimal(str(amount)),
        description='充值',
        status='completed'
    )
    db.add(transaction)
    
    db.commit()
    
    return BaseResponse(message=f"充值成功，当前余额：{float(wallet.balance):.2f}")

@router.post("/withdraw", response_model=BaseResponse)
async def withdraw_from_wallet(
    amount: float,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """从钱包提现"""
    if amount <= 0:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="提现金额必须大于0"
        )
    
    wallet = db.query(Wallet).filter(Wallet.user_id == current_user.id).first()
    if not wallet:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="钱包不存在"
        )
    
    if wallet.balance < Decimal(str(amount)):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="余额不足"
        )
    
    # 更新余额
    wallet.balance -= Decimal(str(amount))
    
    # 记录交易
    transaction = Transaction(
        wallet_id=wallet.id,
        transaction_type='withdrawal',
        amount=-Decimal(str(amount)),
        description='提现',
        status='completed'
    )
    db.add(transaction)
    
    db.commit()
    
    return BaseResponse(message=f"提现成功，当前余额：{float(wallet.balance):.2f}")

@router.get("/transactions", response_model=PaginatedResponse)
async def get_wallet_transactions(
    page: int = 1,
    size: int = 20,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取钱包交易记录"""
    wallet = db.query(Wallet).filter(Wallet.user_id == current_user.id).first()
    if not wallet:
        return PaginatedResponse(items=[], total=0, page=page, size=size, pages=0)
    
    query = db.query(Transaction).filter(Transaction.wallet_id == wallet.id).order_by(Transaction.created_at.desc())
    
    total = query.count()
    transactions = query.offset((page - 1) * size).limit(size).all()
    
    return PaginatedResponse(
        items=transactions,
        total=total,
        page=page,
        size=size,
        pages=(total + size - 1) // size
    )